package com.module.app.utils;

import android.util.Base64;

import com.module.frame.base.BaseFrameApplication;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * @author bsnl_yanxuwen
 * @date 2021/8/13 12:11
 * Description :
 * 名称加密
 * DES  对称加密算法
 */
public class EncodeNameUtils {

    /**
     * 加密
     */
    public static String encode(String name) {
        try {
            DESKeySpec keySpec = new DESKeySpec(getKey().getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);

            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            String encrypedPwd = Base64.encodeToString(cipher.doFinal(name
                    .getBytes("UTF-8")), Base64.URL_SAFE | Base64.NO_WRAP);
            return encrypedPwd;
        } catch (Exception e) {
        }
        return name;
    }

    /**
     * 解密
     */
    public static String decode(String name) {
        try {
            DESKeySpec keySpec = new DESKeySpec(getKey().getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);

            byte[] encryptedWithoutB64 = Base64.decode(name, Base64.URL_SAFE | Base64.NO_WRAP);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
            return new String(plainTextPwdBytes);
        } catch (Exception e) {
        }
        return name;
    }

    private static String getKey(){
        return BaseFrameApplication.getContext().getPackageName();
    }
}
